﻿using Grow.Domain.Object;
using Grow.Domain.Repository.CreateDomainRepository;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System.Linq.Expressions;

namespace Grow.Domain.Repository.EntityFrameworkCore.CreateDomainRepository
{
    public class EntityBuilder<TEntity> : IEntityBuilder<TEntity>
        where TEntity : class, IEntity
    {

        private readonly EntityTypeBuilder<TEntity> _entityTypeBuilder;

        public EntityBuilder(ModelBuilder modelBuilder)
        {
            Type entityType = typeof(TEntity);
            IMutableEntityType? entity = modelBuilder.Model.FindEntityType(entityType);
            entity ??= modelBuilder.Model.AddEntityType(entityType);

            _ = entity.AddProperty(DbConst.IsDelete, typeof(bool));
            _ = entity.AddProperty(DbConst.VersionLock, typeof(Guid));

            _entityTypeBuilder = modelBuilder.Entity<TEntity>();
            _ = _entityTypeBuilder.HasQueryFilter(m => EF.Property<bool>(m, DbConst.IsDelete) == false);

            _ = _entityTypeBuilder.HasKey(a => a.Id);
            _ = _entityTypeBuilder.Property(a => a.Id).HasMaxLength(70).HasComment("Key");
            _ = _entityTypeBuilder.Property(DbConst.VersionLock).IsConcurrencyToken();
        }

        public IEntityPropertyBuilder<TEntity, TProperty> GetEntityPropertyBuilder<TProperty>(Expression<Func<TEntity, TProperty>> propertyExpression)
        {
            return new EntityPropertyBuilder<TEntity, TProperty>(_entityTypeBuilder.Property(propertyExpression));
        }

        public IEntityBuilder<TEntity> HasComment(string comment)
        {
            _ = _entityTypeBuilder.ToTable(a => a.HasComment(comment));
            return this;
        }


    }
}
